const api = require('../../api/api.js');
const util = require('../../utils/util.js');

Page({
  data: {
    records: [],
    inputKey: ''
  },
  onLoad() {
    let that = this;
    wx.getStorage({
      key: 'userId',
      success: function(res) {
        api.queryHistoricalSearchRecord({
          data: {
            userId: res.data
          },
          success(res) {
            console.log(res.data);
            let records = res.data.records;
            that.setData({
              records: records
            });
          }
        });
      },
    })
  },
  formSubmit(e) {
    let kw = e.detail.value.keyword.trim();
    this.goToSearchResultPage(kw);
    this.addRecord(kw);
  },
  confirmed(e) {
    let kw = e.detail.value.trim();
    this.goToSearchResultPage(kw);
    this.addRecord(kw);
  },
  goToSearchResultPage(kw) {
    wx.navigateTo({
      url: `/pages/search-result/search-result?kw=${kw}`,
    })
  },
  addRecord(kw) {
    let that = this;
    wx.getStorage({
      key: 'userId',
      success: function(res) {
        api.addHistoricalSearchRecord({
          data: {
            userId: res.data,
            keyword: kw
          },
          success() {
            that.onLoad();
          }
        });
      },
    })
  },
  tapRecord(e) {
    this.setData({
      inputKey: e.currentTarget.dataset.record
    });
  },
  clear() {
    let that = this;
    wx.showModal({
      title: '提示',
      content: '确定删除所有记录吗？',
      success(e) {
        console.log(e);
        if (e.confirm) {
          wx.getStorage({
            key: 'userId',
            success: function(res) {
              api.clearRecords({
                data: {
                  userId: res.data
                },
                success(res) {
                  that.onLoad();
                  util.showToast('删除成功！', 'success');
                }
              });
            },
          })
        }
      }
    })
  }
})